package com.guoqing.example.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Map;

public class FastJsonUtil {

    public static <T> T parseBean(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }

    public static String parseToString(Object object) {
        return JSON.toJSONString(object);
    }

    public static <T> List<T> parseList(String json, Class<T> clazz) {
        List<T> ts = JSON.parseArray(json, clazz);
        return ts;
    }

    public static <T> T parseType(String json, TypeReference<T> type) {
        T t = JSON.parseObject(json, type);
        return t;
    }

    public static void main(String[] args) {
        String objJson = "[{\"name\":\"zhangsan01\",\"age\":\"21\"}," +
                "{\"name\":\"zhangsan02\",\"age\":\"22\"}]";
        List<Map<String, String>> stringStringMap = parseType(objJson, new TypeReference<List<Map<String, String>>>() {
        });
        System.out.println(stringStringMap);
        List<User> users = parseType(objJson, new TypeReference<List<User>>() {
        });
        System.out.println(users);
        String json = "{\"name\":\"zhangsan\",\"age\":\"21\"}";
        User user = JSON.parseObject(json, User.class);
        System.out.println(user);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class User {
        String name;
        Integer age;
    }

}
